package org.csu.laboratoryequipment.model;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class FileTask implements Callable {
    private String fileName;
    private int start;
    private int end;
    private List<String> output;

    public FileTask(String fileName, int start, int end, List<String> output) {
        this.fileName = fileName;
        this.start = start;
        this.end = end;
        this.output = output;
    }

    //设置任务
    @Override
    public List<String> call() throws Exception {
        try {
            //以GBK的格式对数据进行读取
            List<String> part = Files.readAllLines(Paths.get(fileName), Charset.forName("GBK")).subList(start, end);
            // 过滤掉空行
            part = part.stream()
                    .filter(line -> !line.isEmpty())
                    .collect(Collectors.toList());
            // 对每一行进行处理
            part.forEach(line -> {
                //对每一条数据去除前面四个字段
                line = line.substring(39);
                //以空格为分隔符划分成单个搜索记录
                String s[] = line.split("\\s+");
                //逐行对关键字进行清洗
                // 匹配URL
                Pattern patternUrl1 = Pattern.compile(".*(([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+).*");
                // 匹配域名
                Pattern patternUrl2 = Pattern.compile(".*(([wW]{3}.)?[A-Za-z0-9]+.com).*");
                // 匹配手机号
                Pattern patternPhone = Pattern.compile(".*(((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\\d{8}).*");
                // 匹配电子邮件
                Pattern patternEmail = Pattern.compile(".*([a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+).*");
                // 匹配非字母、数字和汉字的字符
                Pattern patternChar = Pattern.compile("[^(a-zA-Z0-9\\u4e00-\\u9fa5)]");
                // 匹配纯数字
                Pattern patternNum = Pattern.compile("([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])");
                for (String text : s) {
                    if (!(patternChar.matcher(text).matches() || patternNum.matcher(text).matches() || patternEmail.matcher(text).matches() || patternPhone.matcher(text).matches() || (patternUrl1.matcher(text).matches()) || patternUrl2.matcher(text).matches())) {
                        output.add(text);
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return output;
    }
}